﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using OpenTK;
using OpenTK.Graphics.OpenGL4;
using OpenTK.Input;
using System.Drawing;
using OpenTK.Graphics;
using Common;

namespace T02.RedTriangle {
 
    class MyGameWindow : GameWindow {
        public MyGameWindow() {
            this.Load += MyGameWindow_Load;
            this.Resize += MyGameWindow_Resize;
            this.RenderFrame += MyGameWindow_RenderFrame;
            this.Unload += MyGameWindow_Unload;
            this.Width = 1280;
            this.Height = 720;

        }


        private void MyGameWindow_RenderFrame(object sender, FrameEventArgs e) {
            GL.ClearColor(.1f, .1f, .99f, .9f);
            GL.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit);

            Render();

            SwapBuffers();
            ProcessEvents();
        }
        Shader shader;
        Vbo vbo;
        VertexAttribManager attribs;
        float[] g_vertex_buffer_data = {
        -1.0f, -1.0f, 0.0f,
         1.0f, -1.0f, 0.0f,
         0.0f,  1.0f, 0.0f,
    };
        private void MyGameWindow_Load(object sender, EventArgs e) {

            VSync = VSyncMode.Off;
            GL.Enable(EnableCap.DepthTest);
            shader = Shader.CreateFromFile("shader.vs", "shader.fs");
            vbo = new Vbo(BufferTarget.ArrayBuffer, BufferUsageHint.StaticDraw, g_vertex_buffer_data);
            attribs = new VertexAttribManager();
            attribs.AddAttrib(3, vbo);
        }

        private void Render() {
            GL.UseProgram(shader.ID);
            GL.EnableVertexAttribArray(0);
            GL.BindBuffer(BufferTarget.ArrayBuffer, vbo.Id);
            //GL.VertexAttribPointer(0,
            //    3,//this element size
            //    VertexAttribPointerType.Float,
            //    false, //normalized
            //    3 * sizeof(float),//can be 0, means auto
            //    0//offset
            //    );
            //GL.DrawArrays(PrimitiveType.Triangles, 0, 3);

            //GL.DisableVertexAttribArray(0);

            attribs.Enable();
            GL.DrawArrays(PrimitiveType.Triangles, 0, 3);
            attribs.Disable();
        }

        private void MyGameWindow_Resize(object sender, EventArgs e) {
            
            GL.Viewport(0, 0, Width, Height);
        }



        private void MyGameWindow_Unload(object sender, EventArgs e) {
            shader.Dispose();
            vbo.Dispose();
        }

    }
}
